package cn.seocoo.platform.common.utils.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.seocoo.platform.common.constant.PrimaryConstants;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JpushUtil {

    private static Logger LOG = LoggerFactory.getLogger(JpushUtil.class);
    /**
     * 发送系统消息
     */
    public static void sendSystemMessage(String APP_KEY,String MASTER_SECRET, String content) {
        // 生成jpushClient
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_sendSystemMessage(content, PrimaryConstants.SYSTEM_NOTIFY_TITLE);
        try {
            // 开始推送
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("APIConnectionException e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("APIRequestException: e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    /**
     * 构建系统消息通知
     */
    private static PushPayload buildPushObject_sendSystemMessage(String alert, String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios()) // 推送平台 Andorid 与 iOS
                .setAudience(Audience.all()) // 推送设备指定 全部
                .setNotification(Notification.newBuilder() // 通知内容体
                        .setAlert(alert)
                        .addPlatformNotification(AndroidNotification.newBuilder() // 安卓
                                .setTitle(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder() // ios
                                .incrBadge(1)
                                .build())
                        .build())
                .build();
    }

    /**
     * 发送订单消息
     */
    public static void sendOrderMessage(String APP_KEY, String MASTER_SECRET, String userCode, String alert
            ,String title, String msgContent, MessageStatusEnum messageStatus, MessageTypeEnum messageType) {
        // 生成jpushClient
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_sendOrderMessage(userCode, alert,
                title, msgContent, messageStatus, messageType);
        try {
            // 开始推送
            PushResult result = jpushClient.sendPush(payload);
            LOG.warn("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("APIConnectionException e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("APIRequestException: e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    /**
     * 构建订单消息通知
     */
    private static PushPayload buildPushObject_sendOrderMessage(String userCode, String alert, String title
            , String msgContent, MessageStatusEnum messageStatus, MessageTypeEnum messageType) {
        JsonObject sound = new JsonObject();
        sound.add("critical", new JsonPrimitive(1));
        sound.add("name", new JsonPrimitive("default"));
        sound.add("volume", new JsonPrimitive(0.2));
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios()) // 推送平台 Andorid 与 iOS
                .setAudience(Audience.newBuilder() // 推送目标
                        .addAudienceTarget(AudienceTarget.alias(userCode)) // 推动的别名，即用户编号
                        .build())
                .setNotification(Notification.newBuilder() // 通知内容体
                        .setAlert(alert)
                        .addPlatformNotification(AndroidNotification.newBuilder() // 安卓
                                .setTitle(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder() // ios
                                .incrBadge(1)
                                .setSound(sound)
                                .setMutableContent(true)//通知扩展
                                .addExtra("status", messageStatus.getName())
                                .addExtra("type", messageType.getName())
                                .addExtra("msgContent", msgContent)
                                .addExtra("remark", alert)
                                .build())
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(msgContent)
                        .addExtra("status", messageStatus.getName())
                        .addExtra("type", messageType.getName())
                        .addExtra("remark", alert)
                        .build())
                .build();
    }

    /**
     * 推送消息示例
     */
    public static void sendPushAll(String APP_KEY,String MASTER_SECRET, String alert, String title) {
        // 生成jpushClient
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        PushPayload payload = buildPushObject_android_and_ios(alert, title);
        try {
            // 开始推送
            PushResult result = jpushClient.sendPush(payload);
            LOG.warn("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("APIConnectionException e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("APIRequestException: e:{}", e);
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    /**
     * 构建推送对象示例
     */
    private static PushPayload buildPushObject_android_and_ios(String alert, String title) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios()) // 推送平台 Andorid 与 iOS
                .setAudience(Audience.all()) // 推送设备指定 全部
//                .setAudience(Audience.newBuilder() // 推送目标 "tag1" 与 "tag2" 的并集）交（"alias1" 与 "alias2" 的并集）
//                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
//                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
//                        .build())
                .setNotification(Notification.newBuilder() // 通知内容体
                        .setAlert(alert)
                        .addPlatformNotification(AndroidNotification.newBuilder() // 安卓
                                .setTitle(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder() // ios
                                .incrBadge(1)
                                .build())
                        .build())
                .build();
    }
}
